<script lang="ts" setup>
const props = defineProps({
  modelValue: {
    type: Object,
    required: true,
  },
  label: {
    type: Array,
    default: () => ["奖品名称", "奖品图片"],
  },
  prefix: {
    type: String,
    default: "",
  },
  pictureNumber: {
    type: Number,
    default: 1,
  },
  isAddFirstText: {
    type: Boolean,
    default: false,
  },
});

const emits = defineEmits(["update:modelValue"]),
  formRef = inject("formRef");

const form = ref({ thumbnailUrl: "", name: "" });

const detail = computed({
  get: () => {
    let detail = Object.assign({}, form.value, props.modelValue);
    let keys = Object.keys(form.value);
    for (let i = 0; i < keys.length; i++) {
      if (props.modelValue[keys[i]] === undefined) {
        emits("update:modelValue", detail);
        break;
      }
    }
    return detail;
  },
  set: (val) => {
    emits("update:modelValue", val);
  },
});

const uploadChange = () => {
  onChange();
  nextTick(() => {
    formRef.value.validateField(`${props.prefix}thumbnailUrl`);
  });
};

const onChange = () => {
  detail.value = detail.value;
};
</script>
<template>
  <el-form-item
    :label="`${label[0]}:`"
    :prop="`${prefix}name`"
    :rules="[
      { required: true, message: `请输入${label[0]}`, trigger: 'change' },
      {
        min: 2,
        max: 100,
        message: '奖品名称请限制在2至100个字符以内',
        trigger: 'blur',
      },
    ]"
  >
    <el-input
      v-model="detail.name"
      :minlength="2"
      :maxlength="100"
      show-word-limit
      :placeholder="`请填写${label[0]}`"
      @input="onChange"
    ></el-input>
  </el-form-item>
  <el-form-item
    :label="`${label[1]}:`"
    :prop="`${prefix}thumbnailUrl`"
    :rules="[
      { required: true, message: `请上传${label[1]}`, trigger: 'change' },
    ]"
  >
    <Upload
      :isAddFirstText="isAddFirstText"
      :limit="props.pictureNumber"
      v-model="detail.thumbnailUrl"
      file-path="prize/"
      list-type="picture-card"
      @change="uploadChange"
    >
      <el-icon>
        <Plus />
      </el-icon>
    </Upload>
    <div class="upload-tip">
      <div>格式：png/jpg/jpeg</div>
      <div>尺寸: 200px * 200px</div>
    </div>
  </el-form-item>
</template>
<style lang="scss" scoped>
.upload-tip {
  margin-left: 10px;
}
</style>
